package com.iisigroup.log.statistics.internal;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.iisigroup.log.model.LogRecordV1;

public class LogicProcess {
    private final File dir;

    public LogicProcess(final File dir) {
	this.dir = dir;
    }

    public void process(final LogRecordV1 unit) {
	final String account = unit.getAccount();
	if (StringUtils.isBlank(account)) {
	    return;
	}
	final Charset cs = Charset.forName("UTF-8");
	String dirPath = dir.getAbsolutePath();
	try {
	    if (!dir.exists()) {
		Files.createDirectories(dir.toPath());
	    }

	    final Path outPath = Paths.get(dirPath, account);
	    List<String> lines = new ArrayList<String>(1);
	    lines.add(unit.getSrc());
	    if (Files.notExists(outPath)) {
		Files.write(outPath, lines, cs, StandardOpenOption.CREATE_NEW);
	    } else {
		Files.write(outPath, lines, cs, StandardOpenOption.APPEND);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
    public void processList(final List<LogRecordV1> srcList) {
	final	LogRecordV1 unit = srcList.get(0) ;
   	final String account = unit.getAccount();
   	if (StringUtils.isBlank(account)) {
   	    return;
   	}
   	final Charset cs = Charset.forName("UTF-8");
   	String dirPath = dir.getAbsolutePath();
   	try {
   	    if (!dir.exists()) {
   		Files.createDirectories(dir.toPath());
   	    }

   	    final Path outPath = Paths.get(dirPath, account);
   	    
   	    
   	    List<String> lines = new ArrayList<String>(srcList.size());
   	    for(LogRecordV1 unitV  : srcList){
   		  lines.add(unitV.getSrc());
   	    }   	  
   	    if (Files.notExists(outPath)) {
   		Files.write(outPath, lines, cs, StandardOpenOption.CREATE_NEW);
   	    } else {
   		Files.write(outPath, lines, cs, StandardOpenOption.APPEND);
   	    }
   	    
   	    
   	} catch (Exception e) {
   	    e.printStackTrace();
   	}
       }
}
